import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User, LoginForm, RegisterForm } from '@/types'
import { authApi } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string>('')
  const isLogin = ref<boolean>(false)

  // 初始化（从localStorage读取）
  const init = () => {
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    
    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
      isLogin.value = true
    }
  }

  // 登录
  const login = async (form: LoginForm) => {
    try {
      console.log('Store: 调用登录API...', form)
      const res = await authApi.login(form)
      console.log('Store: API响应:', res)
      
      if (res.success && res.data) {
        token.value = res.data.token
        user.value = res.data.user
        isLogin.value = true
        
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('user', JSON.stringify(res.data.user))
        
        console.log('Store: 登录状态已更新', {
          isLogin: isLogin.value,
          user: user.value
        })
        
        ElMessage.success('登录成功！')
        return true
      } else {
        console.log('Store: API返回success=false')
        ElMessage.error(res.message || '登录失败')
        return false
      }
    } catch (error: any) {
      console.error('Store: 登录失败:', error)
      ElMessage.error(error.message || '登录失败，请稍后重试')
      return false
    }
  }

  // 注册
  const register = async (form: RegisterForm) => {
    try {
      const res = await authApi.register(form)
      if (res.success && res.data) {
        token.value = res.data.token
        user.value = res.data.user
        isLogin.value = true
        
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('user', JSON.stringify(res.data.user))
        
        ElMessage.success('注册成功！')
        return true
      }
      return false
    } catch (error) {
      console.error('注册失败:', error)
      return false
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = ''
    isLogin.value = false
    
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    
    ElMessage.success('已退出登录')
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await authApi.getUserInfo()
      if (res.success && res.data) {
        user.value = { ...user.value, ...res.data }
        localStorage.setItem('user', JSON.stringify(user.value))
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }

  // 更新用户信息
  const updateUser = (newUser: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...newUser }
      localStorage.setItem('user', JSON.stringify(user.value))
    }
  }

  return {
    user,
    token,
    isLogin,
    init,
    login,
    register,
    logout,
    getUserInfo,
    updateUser
  }
})

